<template>
    <!-- 表单查询 -->
    <el-card style="margin-bottom: 10px;">
        <el-form :inline="true" class="demo-form-inline" style="margin-top: 10px;">
            <el-form-item label="岗位">
                <el-input v-model="pageinfo.PositionName" placeholder="请输入岗位名称搜索" clearable />
            </el-form-item>
            <el-form-item label="状态">
                <el-select v-model="pageinfo.Status" placeholder="请选择" clearable>
                    <el-option label="启用" value="1" />
                    <el-option label="停用" value="0" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="success" @click="getPositionList">查询</el-button>
                <el-button type="info" @click="resetSearch">重置</el-button>
            </el-form-item>
        </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <el-card style="margin-bottom: 10px;">
        <el-button type="primary" @click="handleAdd">
            <el-icon>
                <Plus />
            </el-icon>新增
        </el-button>
        <el-button @click="handleBatchDelete" type="danger">批量删除</el-button>
        <el-button @click="handleBatchEnable" type="success">批量启用</el-button>
        <el-button @click="handleBatchDisable" type="warning">批量停用</el-button>
    </el-card>

    <!-- 岗位列表数据 -->
    <el-card style="margin-bottom: 10px;">
        <el-table ref="multipleTableRef" :data="tableData" row-key="positionId" style="width: 100%; margin-top: 10px;"
            @selection-change="handleSelectionChange" height="440px">
            <el-table-column type="selection" width="55" fixed="left" />
            <el-table-column type="index" label="序号" width="80" fixed="left" />
            <el-table-column property="positionCode" label="岗位编号" width="120" />
            <el-table-column property="positionName" label="岗位名称" width="150" />
            <el-table-column property="positionSort" label="排序" width="80" />
            <el-table-column property="positionState" label="状态" width="80">
                <template #default="scope">
                    <span v-if="scope.row.positionState === 1">启用</span>
                    <span v-else-if="scope.row.positionState === 0">停用</span>
                </template>
            </el-table-column>
            <el-table-column property="positionNote" label="备注" width="120" show-overflow-tooltip />
            <el-table-column label="操作" fixed="right" width="170">
                <template #default="scope">
                    <el-button link size="small" type="warning" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button link size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
    </el-card>

    <!-- 分页 -->
    <el-card>
        <el-pagination v-model:current-page="pageinfo.Pageindex" v-model:page-size="pageinfo.PageSize"
            :page-sizes="[10, 20, 30, 40]" :background="true" layout="total, sizes, prev, pager, next, jumper"
            :total="pageinfo.listCount" />
    </el-card>

    <!-- 新增/编辑岗位对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" @close="handleDialogClose">
        <el-form ref="positionFormRef" :model="positionForm" :rules="positionFormRules" label-width="100px">
            <el-form-item label="岗位编号 *" prop="positionNumber">
                <el-input v-model="positionForm.positionCode" placeholder="自动获取系统编号" readonly class="form-input">
                    <template #append>
                        <el-button @click="generatePositionCode" :loading="generatingCode">自动生成</el-button>
                    </template>
                </el-input>
            </el-form-item>
            <el-form-item label="岗位名称 *" prop="positionName">
                <el-input v-model="positionForm.positionName" placeholder="请输入岗位名称" />
            </el-form-item>
            <el-form-item label="排序" prop="positionSort">
                <el-input v-model.number="positionForm.positionSort" placeholder="请输入排序" type="number" />
            </el-form-item>
            <el-form-item label="状态" prop="positionState">
                <el-radio-group v-model="positionForm.positionState">
                    <el-radio :label="1">启用</el-radio>
                    <el-radio :label="0">停用</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="备注" prop="positionNote">
                <el-input v-model="positionForm.positionNote" type="textarea" :rows="4" placeholder="请输入备注" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="success" @click="handleSave">保存</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, watch } from 'vue'
import myaxios from "@/http/MyAxios";
import { ElMessage, ElMessageBox, type TableInstance, type FormInstance, type FormRules } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

// 分页查询条件
const pageinfo = reactive({
    pageCount: 0,
    listCount: 0,
    Pageindex: 1,
    PageSize: 10,
    PositionName: "",
    Status: null,
})

// 多选
const multipleTableRef = ref<TableInstance>()
const multipleSelection = ref<any[]>([])

const handleSelectionChange = (val: any[]) => {
    multipleSelection.value = val
}

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('新增')
const positionFormRef = ref<FormInstance>()
const isEdit = ref(false)
const generatingCode = ref(false)

// 岗位表单数据
const positionForm = reactive({
    positionId: null,
    positionCode: '',
    positionName: '',
    positionSort: 0,
    positionState: 1,
    positionNote: '',
})

// 表单验证规则
const positionFormRules: FormRules = {
    positionCode: [
        { required: true, message: '请输入岗位编号', trigger: 'blur' }
    ],
    positionName: [
        { required: true, message: '请输入岗位名称', trigger: 'blur' }
    ],
}

// 岗位列表数据
const tableData = ref([])

// 获取岗位列表
const getPositionList = () => {
    myaxios({
        url: "/api/Position/GetPositionList",
        method: "get",
        params: {
            Pageindex: pageinfo.Pageindex,
            PageSize: pageinfo.PageSize,
            PositionName: pageinfo.PositionName,
            Status: pageinfo.Status,
        }
    })
        .then(res => {
            if (res.data.code === 200) {
                tableData.value = res.data.data?.data || [];
                pageinfo.listCount = res.data.data?.listCount || 0;
                pageinfo.pageCount = res.data.data?.pageCount || 0;
            } else {
                ElMessage.error(res.data.message || '获取岗位列表失败');
            }
        })
        .catch(err => {
            console.log(err);
            ElMessage.error('获取岗位列表失败');
        })
}

// 重置搜索
const resetSearch = () => {
    pageinfo.PositionName = "";
    pageinfo.Status = null;
    pageinfo.Pageindex = 1;
    getPositionList();
}

// 新增
const handleAdd = () => {
    dialogTitle.value = '新增'
    isEdit.value = false
    resetPositionForm()
    dialogVisible.value = true
}

// 重置表单
const resetPositionForm = () => {
    positionForm.positionId = null
    positionForm.positionCode = ''
    positionForm.positionName = ''
    positionForm.positionSort = 0
    positionForm.positionState = 1
    positionForm.positionNote = ''
    // 清除表单验证
    positionFormRef.value?.clearValidate()
}

// 对话框关闭
const handleDialogClose = () => {
    resetPositionForm()
}

// 生成岗位编号
const generatePositionCode = async () => {
    generatingCode.value = true
    try {
        // 首先尝试直接向后端请求生成
        const res = await myaxios({
            url: '/api/Number/GenerateNumber',
            method: 'get',
            params: {
                targetCode: 'Position',
                targetName: '岗位'
            }
        })
        if (res?.data?.code === 200 && res?.data?.data) {
            positionForm.positionCode = res.data.data
            ElMessage.success('编号生成成功')
        } else {
            throw new Error(res?.data?.message || '生成编号失败')
        }
    } catch (err: any) {
        console.error('生成岗位编号失败:', err)
        // 备用：根据编号规则生成
        try {
            const ruleRes = await myaxios({
                url: '/api/Number/QueryNumberingRules',
                method: 'get',
                params: {
                    targetCode: 'Position',
                    targetName: '岗位'
                }
            })
            if (ruleRes?.data?.code === 200 && Array.isArray(ruleRes.data.data) && ruleRes.data.data.length > 0) {
                const rule = ruleRes.data.data[0]
                const now = new Date()
                const pad = (n: number, len = 2) => `${n}`.padStart(len, '0')
                const order = ['YYYY', 'YY', 'MM', 'DD', 'HH', 'MI', 'SS']
                const segments = (rule.timeRule || '').split(',').filter(Boolean).sort((a: string, b: string) => {
                    const indexA = order.indexOf(a)
                    const indexB = order.indexOf(b)
                    if (indexA === -1 && indexB === -1) return 0
                    if (indexA === -1) return 1
                    if (indexB === -1) return -1
                    return indexA - indexB
                })
                const datePart = segments.map((seg: string) => {
                    switch (seg) {
                        case 'YYYY': return String(now.getFullYear())
                        case 'YY': return String(now.getFullYear()).slice(-2)
                        case 'MM': return pad(now.getMonth() + 1)
                        case 'DD': return pad(now.getDate())
                        case 'HH': return pad(now.getHours())
                        case 'MI': return pad(now.getMinutes())
                        case 'SS': return pad(now.getSeconds())
                        default: return ''
                    }
                }).join('')
                const seq = '1'.padStart(rule.serialLength || 3, '0')
                positionForm.positionCode = `${rule.codePrefix || ''}${datePart}${seq}`
                ElMessage.success('编号生成成功')
            } else {
                ElMessage.warning('未找到对应的编号规则，请先配置编号规则')
            }
        } catch (ruleErr) {
            console.error('获取岗位编号规则失败:', ruleErr)
            ElMessage.error('生成编号失败，请稍后重试')
        }
    } finally {
        generatingCode.value = false
    }
}

// 保存岗位
const handleSave = async () => {
    if (!isEdit.value && !positionForm.positionCode) {
        await generatePositionCode()
        if (!positionForm.positionCode) return
    }
    positionFormRef.value?.validate((valid) => {
        if (valid) {
            const url = isEdit.value ? '/api/Position/UpdatePosition' : '/api/Position/CreatePosition'
            const method = isEdit.value ? 'post' : 'post'

            myaxios({
                url: url,
                method: method,
                data: positionForm
            })
                .then(res => {
                    if (res.data.code === 200) {
                        ElMessage.success(res.data.message || '保存成功')
                        dialogVisible.value = false
                        getPositionList() // 刷新列表
                    } else {
                        ElMessage.error(res.data.message || '保存失败')
                    }
                })
                .catch(err => {
                    console.log('保存岗位错误:', err)
                    if (err.response && err.response.data) {
                        if (err.response.data.errors) {
                            // 处理验证错误
                            const errors = err.response.data.errors
                            const errorMessages = []
                            for (const field in errors) {
                                errorMessages.push(...errors[field])
                            }
                            ElMessage.error(errorMessages.join('; '))
                        } else {
                            ElMessage.error(err.response.data.message || '保存失败')
                        }
                    } else {
                        ElMessage.error('保存失败')
                    }
                })
        } else {
            ElMessage.warning('请填写必填项')
        }
    })
}

// 编辑
const handleEdit = (row: any) => {
    dialogTitle.value = '编辑'
    isEdit.value = true
    resetPositionForm()
    dialogVisible.value = true

    // 反填表单数据
    positionForm.positionId = row.positionId || null
    positionForm.positionCode = row.positionCode || ''
    positionForm.positionName = row.positionName || ''
    positionForm.positionSort = row.positionSort || 0
    positionForm.positionState = row.positionState !== undefined ? row.positionState : 1
    positionForm.positionNote = row.positionNote || ''
}

// 删除单个岗位
const handleDelete = (row: any) => {
    ElMessageBox.confirm(
        '确认删除这条岗位信息吗?',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            try {
                const res = await myaxios.delete(`/api/Position/DeletePositions?PositionId=${row.positionId}`)
                if (res.data?.code === 200) {
                    ElMessage.success(res.data.message || '删除成功')
                    getPositionList()
                } else {
                    ElMessage.error(res.data?.message || '删除失败')
                }
            } catch (error: any) {
                console.error('删除岗位失败:', error)
                if (error.response?.status === 404) {
                    ElMessage.error('删除接口不存在，请检查后端API')
                } else if (error.response?.data?.message) {
                    ElMessage.error(error.response.data.message)
                } else {
                    ElMessage.error('删除失败，请稍后重试')
                }
            }
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消',
            })
        })
}

// 批量删除
const handleBatchDelete = () => {
    if (multipleSelection.value.length === 0) {
        ElMessage.warning('请选择要删除的岗位');
        return;
    }
    ElMessageBox.confirm(
        '确认删除这些岗位信息吗?',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            const positionIds = multipleSelection.value.map((x: any) => x.positionId);
            myaxios.post("/api/Position/DeletePositions", {
                ids: positionIds
            })
                .then(res => {
                    if (res.data?.code === 200) {
                        ElMessage.success(res.data.message || '删除成功')
                        getPositionList()
                    } else {
                        ElMessage.error(res.data?.message || '删除失败')
                    }
                })
                .catch(err => {
                    console.error('批量删除岗位失败:', err)
                    if (err.response?.data?.message) {
                        ElMessage.error(err.response.data.message)
                    } else {
                        ElMessage.error('删除失败，请稍后重试')
                    }
                })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消',
            })
        })
}

// 批量启用
const handleBatchEnable = () => {
    if (multipleSelection.value.length === 0) {
        ElMessage.warning('请选择要启用的岗位');
        return;
    }
    const positionIds = multipleSelection.value.map((x: any) => x.positionId);
    myaxios({
        url: "/api/Position/EnablePositions",
        method: "post",
        data: {
            ids: positionIds
        }
    })
        .then(res => {
            if (res.data.code === 200) {
                getPositionList();
                ElMessage.success(res.data.message || '启用成功');
            } else {
                ElMessage.error(res.data.message || '启用失败');
            }
        })
        .catch(err => {
            console.log(err);
            ElMessage.error('启用失败');
        })
}

// 批量停用
const handleBatchDisable = () => {
    if (multipleSelection.value.length === 0) {
        ElMessage.warning('请选择要停用的岗位');
        return;
    }
    const positionIds = multipleSelection.value.map((x: any) => x.positionId);
    myaxios({
        url: "/api/Position/DisablePositions",
        method: "post",
        data: {
            ids: positionIds
        }
    })
        .then(res => {
            if (res.data.code === 200) {
                getPositionList();
                ElMessage.success(res.data.message || '停用成功');
            } else {
                ElMessage.error(res.data.message || '停用失败');
            }
        })
        .catch(err => {
            console.log(err);
            ElMessage.error('停用失败');
        })
}

// 钩子函数
onMounted(() => {
    getPositionList(); // 岗位信息请求
})

// 侦听器
watch(pageinfo, () => {
    getPositionList(); // 岗位信息请求
}, { deep: true })
</script>

<style>
.demo-form-inline .el-input {
    --el-input-width: 220px;
}

.demo-form-inline .el-select {
    --el-select-width: 220px;
}

:deep(.form-input) {
    width: 400px !important;
}

:deep(.form-input .el-input__wrapper) {
    width: 100% !important;
}

:deep(.form-input.el-input-number) {
    width: 400px !important;
}
</style>